package yc.bluetooth.androidble;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 搜索到的设备列表适配器
 */
public class LVDevicesAdapter extends BaseAdapter {

    private Context context;
    private List<BLEDevice> list;

    public LVDevicesAdapter(Context context) {
        this.context = context;
        list = new ArrayList<>();
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int i) {
        if (list == null) {
            return null;
        }
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        DeviceViewHolder viewHolder;
        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.layout_lv_devices_item, null);
            viewHolder = new DeviceViewHolder();
            viewHolder.tvDeviceName = view.findViewById(R.id.tv_device_name);
            viewHolder.tvDeviceAddress = view.findViewById(R.id.tv_device_address);
            viewHolder.tvDeviceRSSI = view.findViewById(R.id.tv_device_rssi);
            view.setTag(viewHolder);
        } else {
            viewHolder = (DeviceViewHolder) view.getTag();
        }

        if (list.get(i).getBluetoothDevice().getName() == null) {
            viewHolder.tvDeviceName.setText("NULL");
        } else {
            viewHolder.tvDeviceName.setText(list.get(i).getBluetoothDevice().getName());
        }

        viewHolder.tvDeviceAddress.setText(list.get(i).getBluetoothDevice().getAddress());
        viewHolder.tvDeviceRSSI.setText("RSSI：" + list.get(i).getRSSI());

        return view;
    }

    /**
     * 初始化所有设备列表
     *
     * @param bluetoothDevices
     */
    public void addAllDevice(List<BLEDevice> bluetoothDevices) {
        if (list != null) {
            list.clear();
            list.addAll(bluetoothDevices);
            notifyDataSetChanged();
        }

    }

    // /**
    //  * 添加列表子项
    //  *
    //  * @param bleDevice
    //  */
    // public void addDevice(BLEDevice bleDevice) {
    //     if (list == null) {
    //         return;
    //     }
    //     // 判断搜索对象
    //     if (bleDevice == null) {
    //         return;
    //     }
    //     // 如果名字是null或者空忽略
    //     if (TextUtils.isEmpty(bleDevice.getBluetoothDevice().getName())) {
    //         return;
    //     }
    //     // 如果已经包含?
    //     if (!list.contains(bleDevice)) {
    //         list.add(bleDevice);
    //     }
    //     notifyDataSetChanged();   //刷新
    // }
    public static void removeAndAddUniqueAddress(List<BLEDevice> bleDeviceList, BLEDevice givenBLEDevice) {
        // 创建一个新的列表来存储与给定BLEDevice不同的address元素
        List<BLEDevice> devicesWithDifferentAddress = new ArrayList<>();
        // 使用stream()和filter()方法查找与给定BLEDevice的address属性相同的元素
        List<BLEDevice> devicesWithSameAddress = null;

        devicesWithSameAddress = bleDeviceList.stream()
                .filter(bleDevice -> bleDevice.getAddress().equals(givenBLEDevice.getAddress()))
                .collect(Collectors.toList());

        // 将与给定BLEDevice不同的address元素添加到新的列表中
        devicesWithDifferentAddress.addAll(bleDeviceList);
        devicesWithDifferentAddress.removeAll(devicesWithSameAddress);

        //添加唯一
        devicesWithDifferentAddress.add(givenBLEDevice);

        // 更新原始的BLEDevice列表，使其只包含与给定BLEDevice不同的address元素
        bleDeviceList.clear();
        bleDeviceList.addAll(devicesWithDifferentAddress);
    }
    public void addDevice(BLEDevice bleDevice){
        if(list == null || bleDevice == null){
            return;
        }
        // 如果名字是null或者空忽略
        if (TextUtils.isEmpty(bleDevice.getBluetoothDevice().getName())) {
            return;
        }
        removeAndAddUniqueAddress(list,bleDevice);

        //--sort by rssi
        Collections.sort(list, new Comparator<BLEDevice>() {
            @Override
            public int compare(BLEDevice bleDevice1, BLEDevice bleDevice2) {
                int ret = Integer.compare(bleDevice2.getRSSI(),bleDevice1.getRSSI());
                return ret;
            }
        });

        notifyDataSetChanged();   //刷新
    }

    /**
     * 清空列表
     */
    public void clear() {
        if (list != null) {
            list.clear();
        }
        notifyDataSetChanged(); //刷新
    }

    class DeviceViewHolder {

        TextView tvDeviceName;
        TextView tvDeviceAddress;
        TextView tvDeviceRSSI;
    }

}
